package com.shortUrl.starter.verticle;

import com.shortUrl.starter.util.MysqlUtils;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.SqlClient;
import io.vertx.sqlclient.Tuple;

public class DbVerticle extends AbstractVerticle {
    SqlClient mysqlClient;

    @Override
    public void start(Promise<Void> startPromise) throws Exception {
        createPool();
        System.out.println("数据库连接成功");
        createService();
    }

    public void createPool() {
        mysqlClient = MysqlUtils.getMysqlClient(vertx);
    }

    public void createService() {
        EventBus eventBus = vertx.eventBus();

        eventBus.<JsonObject>consumer("saveBean").handler(handler -> {
            JsonObject shortUrl = handler.body();
            System.out.println(shortUrl);
            mysqlClient.preparedQuery("insert into short_url(short_url,long_url) value(?,?)")
                    .execute(Tuple.of(shortUrl.getValue("shortUrl"), shortUrl.getValue("longUrl")))
                    .onSuccess(saveHandler -> {
                        handler.reply("success");
                    }).onFailure(fail -> {
                        fail.printStackTrace();
                        handler.reply("error");
                    });
        });
        eventBus.<String>consumer("getBean").handler(consumer -> {
            String shortUrl = consumer.body();
            mysqlClient.preparedQuery("select * from short_url where short_url = ?")
                    .execute(Tuple.of(shortUrl)).onSuccess(selectHandler -> {
                        // selectHandler.value()
                        RowSet<Row> rowSet = selectHandler.value();
                        JsonArray jsonArray = new JsonArray();
                        rowSet.forEach(row->{
                            jsonArray.add(row.toJson());
                        });
                        consumer.reply(jsonArray);
                    });
        });
    }
}
